﻿using System;

namespace ConsoleApp.Infrastructure.Rmq
{
    public class RmqQueueCommonOperate<T> where T : class
    {
        public delegate bool ConsumerWorker(T t);

        private class Consumer : RmqComsumerWorkerBase<T>
        {
            private ConsumerWorker Worker;
			public Consumer(RmqOption rmqOption, string queueName, ConsumerWorker worker, int threadCount = 1, bool autoAckOk = false, bool failEnqueue = false):base(rmqOption)
            {
                QueueName = queueName;
                ConsumerCount = threadCount;
                Worker = worker;
                AutoAckOk = autoAckOk;
				RmqOption = rmqOption;
                FailEnqueue = failEnqueue;
            }

            protected override bool HandleComingMessage(T messageDto)
            {
                try
                {
                    return Worker(messageDto);
                }
                catch (Exception ex)
                {
                    RmqLogHelper.WriteError("消费队列异常:" + ex);
                }

                return true;
            }
        }

        //private RmqUrlEnum _rmqUrlEnum;

        private RmqMessageProducer _service { get; set; }

        private string _queueName { get; set; }

        private RmqHttpApiService _rmqHttpApi { get; set; }

        private string _exchange { get; set; }

        private RmqMessageProducer _producer { get; set; }


		protected RmqOption _rmqOption { get; set; }

		public RmqQueueCommonOperate(RmqOption rmqOption, string exchange, string queueName)
        {
			_rmqOption = rmqOption;
            _queueName = queueName;
            _exchange = exchange;
            _rmqHttpApi = new RmqHttpApiService(_rmqOption);
        }

        public void Enqueue(T t, string routeKey = "", RmqMessagePriorityLevel priorityLevel = RmqMessagePriorityLevel.Normal, int deliveryMode = 1)
        {
            if (string.IsNullOrEmpty(routeKey))
            {
                routeKey = _exchange + "." + _queueName;
            }

            RmqMessageProducer.MessageSend(_rmqOption, _exchange, routeKey, t, new RmqMessageProps
            {
                Priority = priorityLevel,
                DeliveryMode = deliveryMode
            });
        }

        public int GetCount()
        {
            return _rmqHttpApi.GetMessageCount(_queueName);
        }

        public void StartConsumer(ConsumerWorker worker, int threadCount = 1)
        {
            new Consumer(_rmqOption, _queueName, worker, threadCount).Start();
        }
    }
}
